<template>
    <div class="page" v-if="cartInfo.length > 0">
        <app-header>
            <a slot="left" href="javascript:;" class="go-back" @click="back"></a>
            <span slot="title">购物车</span>
        </app-header>
        <div class="cart-box">
            <div class="cart-items" v-for="(item,index) in cartInfo" :key="item.fuid" v-if="item.product_list.length > 0">
                <div class="cart-items-head flexbox items-center">
                    <input type="checkbox" name="company" :id="'company'+item.fuid" class="checkbox" />
                    <label :for="'company'+item.fuid" class="label" @click.stop="company_all(index,$event)"></label>
                    <a class="company-name" href="javascript:;">{{item.fname}}</a>
                    <a class="company-edit" href="javascript:;" @click="edit(index,$event)">编辑</a>
                </div>
                <ul class="cart-item-pro">
                    <li v-for="(info,key) in item.product_list" :key="info.cartid" @touchstart.stop="touchStart($event)" @touchmove.stop="touchMove($event)" @touchend.stop="touchEnd($event)">
                        <div class="item-pro-info flexbox">
                            <input type="checkbox" name="pro" v-model="cartids" :id="'pro'+info.cartid" :value="info.cartid" class="checkbox" />
                            <label :for="'pro'+info.cartid" class="label" @click.stop="check_pro(index, key, item.fuid, info.cartid)"></label>
                            <div class="item-pro flexbox">
                                <div class="item-pro-thumb">
                                    <img class="img-responsive row" :src="info.image" />
                                </div>
                                <div class="pro-info">
                                    <h2 v-text="info.pname"></h2>
                                    <p v-text="info.clsdata"></p>
                                    <div class="cart-price-qty flexbox items-center">
                                        <div class="cart-price">{{info.cartprice | Currency}}</div>
                                        <div class="edit-quantity flexbox" v-if="editids[index]==index">
                                            <button class="decrease" @click="updateCount(false,index,key)">-</button>
                                            <input type="number" id="number" v-model="info.nums" :value="info.nums">
                                            <button class="increase" @click="updateCount(true,index,key)">+</button>
                                        </div>
                                        <div v-else class="cart-qty" v-text="'x'+info.nums"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="item-del-btn flexbox items-center justify-center" @click="del(index,key,item.fuid,info.cartid)">删除</div>
                    </li>
                </ul>
            </div>
            <div class="cart-footer flexbox">
                <div class="checked-all flexbox items-center" @click.stop="checkall">
                    <input type="checkbox" name="checkall" id="checkall" class="checkbox" />
                    <label for="checkall" class="label"></label> 全选
                </div>

                <div class="total-price">
                    合计：
                    <span>{{total.toFixed(2)}}</span> 元
                </div>
                <div class="buy-btn" @click="submit">立即结算({{cartids.length}})</div>
            </div>
        </div>
    </div>
</template>
<script>
import mixin from "@/mixin";
import appHeader from "@/components/common/HeadBar";
export default {
  data() {
    return {
      cartInfo: [],
      cartids: [],
      editids: [],
      initX: "", // 触摸位置
      moveX: "", // 滑动时的位置
      movedX: 0, // 移动距离
      objX: 0 // 目标对象位置
    };
  },
  mixins: [mixin],
  components: {
    appHeader
  },
  computed: {
    total() {
      return this.totalPrice();
    }
  },
  methods: {
    // 初始化
    load_cart_list() {
      this.api.get_cart_list().then(response => {
        this.cartInfo = response.data.cartlist;
      });
    },
    touchStart(event) {
      let target = event.target;
      while (target && (!target.nodeName || target.nodeName !== "LI")) {
        target = target.parentNode;
      }
      if (target) {
        this.initX = event.targetTouches[0].pageX;
        this.objX =
          target.style.WebkitTransform
            .replace(/translateX\(/g, "")
            .replace(/rem\)/g, "") * 1;
      }
    },
    touchMove(event) {
      let target = event.target;
      while (target && (!target.nodeName || target.nodeName !== "LI")) {
        target = target.parentNode;
      }
      if (this.objX == 0) {
        if (target) {
          this.moveX = event.targetTouches[0].pageX;
          this.movedX = this.moveX - this.initX;
          if (this.movedX >= 0) {
            target.style = "";
          } else if (this.movedX < 0) {
            var l = Math.abs(this.movedX) / 75;
            target.style.WebkitTransform = "translateX(" + -l + "rem)";
            if (l > 2.04) {
              // 按钮宽度153 / 默认字体 75 = 2.04
              l = 2.04;
              target.style.WebkitTransform = "translateX(" + -l + "rem)";
            }
          }
        }
      } else if (this.objX < 0) {
        if (target) {
          this.moveX = event.targetTouches[0].pageX;
          this.movedX = this.moveX - this.initX;
          if (this.movedX >= 0) {
            var r = (-153 + Math.abs(this.movedX)) / 75;
            target.style.WebkitTransform = "translateX(" + r + "rem)";
            if (r >= 0) {
              r = 0;
              target.style.WebkitTransform = "translateX(" + r + "rem)";
            }
          } else {
            target.style = "";
          }
        }
      }
    },
    touchEnd(event) {
      let target = event.target;
      while (target && (!target.nodeName || target.nodeName !== "LI")) {
        target = target.parentNode;
      }
      if (target) {
        this.objX =
          target.style.WebkitTransform
            .replace(/translateX\(/g, "")
            .replace(/rem\)/g, "") * 1;
        if (this.objX > -76 / 75) {
          target.style = "";
        } else {
          target.style.WebkitTransform = "translateX(" + -2.04 + "rem)";
        }
      }
    },
    // 计算总价
    totalPrice() {
      var total = 0;
      for (let i in this.cartInfo) {
        for (let j in this.cartInfo[i].product_list) {
          if (
            this.in_array(this.cartInfo[i].product_list[j].cartid, this.cartids)
          ) {
            //计算已选中商品价格总和
            total +=
              this.cartInfo[i].product_list[j].nums *
              this.cartInfo[i].product_list[j].cartprice;
          }
        }
      }
      return parseInt(total);
    },
    // 删除
    del(index, key, fuid, cartid) {
      let checkAllStatus = true;
      let data = this.cartInfo[index];
      for (let i in data.product_list) {
        if (cartid === data.product_list[i].cartid) {
          this.cartInfo[index].product_list.splice(i, 1);
          break;
        }
      }
      for (let j in this.cartids) {
        if (cartid === this.cartids[j]) {
          this.cartids.splice(j, 1);
          break;
        }
      }
      if (this.cartids.length <= 0) checkAllStatus = false;
      this.allIsChecked(checkAllStatus, data);
    },
    // 全选/反选当前商铺列表
    company_all(index, event) {
      let id = event.target.getAttribute("for");
      let checkbox = document.getElementById(id);
      let data = this.cartInfo[index];
      let delIndex = -1;
      let checkAllStatus = true;
      if (checkbox.checked) {
        // 全反选
        for (let i in data.product_list) {
          for (let j in this.cartids) {
            if (this.cartids[j] === data.product_list[i].cartid) {
              delIndex = j;
              break;
            }
          }
          checkAllStatus = false;
          this.cartids.splice(delIndex, 1);
        }
      } else {
        // 全选
        for (let i in data.product_list) {
          if (this.in_array(data.product_list[i].cartid, this.cartids))
            continue; // 如果已存在 退出
          this.cartids.push(data.product_list[i].cartid);
        }
      }
      this.allIsChecked(checkAllStatus, data);
    },
    //商品选中
    check_pro(index, key, fuid, cartid) {
      /**
     * index 当前店铺数据位置
     * key 当前选择商品的位置
     * fuid 店铺id
     * cartid 商品id
     * 这里的this.cartids获取的是上一次的记录
    */
      let data = this.cartInfo[index]; // 当前选中的商品所属位置数据
      let checkShopStatus = true; // 当前商品所属商铺全选按钮，true为选中状态
      let checkAllStatus = true; //底部全选按钮
      let id = "company" + fuid; // 当前商铺按钮id
      if (this.in_array(cartid, this.cartids)) {
        // 如果this.cartids中存在当前商品cartid，全选按钮设置未选中状态
        checkAllStatus = checkShopStatus = false;
      } else {
        for (let i in data.product_list) {
          if (data.product_list[i].cartid == cartid) continue; // 相等，跳出本次for
          if (!this.in_array(data.product_list[i].cartid, this.cartids)) {
            checkAllStatus = checkShopStatus = false;
            break;
          }
        }
      }
      this.allIsChecked(checkAllStatus, data);
      document.getElementById(id).checked = checkShopStatus;
    },
    // 全部选中
    checkall() {
      let isChecked = false;
      let checkbox = document.getElementById("checkall");
      let companyCheckBox = document.querySelectorAll("input[name='company']");
      if (checkbox.checked) {
        isChecked = false;
        this.cartids = [];
      } else {
        isChecked = true;
        for (let i in this.cartInfo) {
          for (let j in this.cartInfo[i].product_list) {
            if (
              this.in_array(
                this.cartInfo[i].product_list[j].cartid,
                this.cartids
              )
            )
              continue; // 如果已存在 退出
            this.cartids.push(this.cartInfo[i].product_list[j].cartid);
          }
        }
      }
      for (let i = 0; i < companyCheckBox.length; i++) {
        companyCheckBox[i].checked = isChecked;
      }
      checkbox.checked = isChecked;
    },
    //检测数组是否存在指定值
    in_array(key, array) {
      for (var i in array) {
        if (array[i] == key) {
          return true;
        }
      }
      return false;
    },
    // 全选按钮状态
    allIsChecked(checkAllStatus, data) {
      let allCheckbox = document.getElementById("checkall");
      for (let i in this.cartInfo) {
        if (!checkAllStatus) {
          break;
        } else if (this.cartInfo[i].fuid == data.fuid) {
          continue;
        }
        for (let j in this.cartInfo[i].product_list) {
          if (
            !this.in_array(
              this.cartInfo[i].product_list[j].cartid,
              this.cartids
            )
          ) {
            checkAllStatus = false;
          }
        }
      }
      allCheckbox.checked = checkAllStatus;
    },
    //编辑商品
    edit(index, event) {
      let btnText = event.target.innerHTML;
      if (btnText == "完成") {
        event.target.innerHTML = "编辑";
        this.$set(this.editids, index, -1);
        this.totalPrice();
      } else {
        event.target.innerHTML = "完成";
        this.$set(this.editids, index, index);
      }
    },
    updateCount(flag, index, key) {
      let nums = parseInt(this.cartInfo[index].product_list[key].nums);
      if (flag) {
        nums += 1;
      } else {
        if (nums <= 1) return false;
        nums -= 1;
      }
      this.cartInfo[index].product_list[key].nums = nums;
      this.totalPrice();
    },
    submit() {
      if (this.cartids.length <= 0) {
        this.$Toast("您还没有选择宝贝哦~");
      }
    }
  },
  created() {
    // 初始化数据
    this.load_cart_list();
  }
};
</script>
<style src="@/assets/scss/cart.scss" lang="scss"></style>
